#include "param.h"
#include "utils.h"
#include "crc16.h"
#include "rtos.h"
#include "string.h"
#include "spi_flash.h"
#include "elog.h"

param_t param;

SemaphoreHandle_t  mutex_param=NULL;

void param_set_def(void);

void __param_set(int offset,int len,void *value)
{
	xSemaphoreTake(mutex_param,portMAX_DELAY);
	memcpy(&param+offset,value,len);
	xSemaphoreGive(mutex_param);
}

void __param_get(int offset,int len,void *value)
{
	xSemaphoreTake(mutex_param,portMAX_DELAY);
	memcpy(value,(u8*)&param+offset,len);
	xSemaphoreGive(mutex_param);
}

void load_param(void)
{
	u16 crc16=0;
	spi_flash_read((u8*)&param,PARAM_ADDR,sizeof(param_t));
	crc16=cal_crc16((u8*)&param,OFFSET_OF(param_t,crc16));
	if(crc16!=param.crc16)
	{
		log_d(" param check failed,set default ");
		param_set_def();
	}
}


void save_param(void)
{
	xSemaphoreTake(mutex_param,portMAX_DELAY);
	param.crc16=cal_crc16((u8*)&param,OFFSET_OF(param_t,crc16));
	spi_flash_write((u8*)&param,PARAM_ADDR,sizeof(param_t));
	xSemaphoreGive(mutex_param);
}

void param_set_def(void)
{
	param_t __param;
	memset(&__param,0,sizeof(param_t));
	memcpy(__param.sta_ap_ssid,"JZ_TECH",sizeof("JZ_TECH"));
	memcpy(__param.sta_ap_pass,"Jz123456778",sizeof("Jz123456778"));
	memcpy(__param.server_ip,"172.18.118.198",sizeof("172.18.118.198"));
	__param.server_port=9563;
	__param_set(0,sizeof(param_t),&__param);
	save_param();
}




